package com.vilen.weixin.kit;

import com.fasterxml.jackson.databind.JsonNode;
import com.vilen.basic.util.JsonUtil;
import com.vilen.basic.util.PropertiesUtil;
import com.vilen.weixin.model.WeixinFinalValue;
import com.vilen.weixin.web.servlet.WeixinContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * Created by Administrator on 2016/2/14.
 */
public class WeixinBasicKit {
    /**
     * 初始化一些值，方便测试类使用
     */
    public static void setWeixinContext() {
        Properties properties = PropertiesUtil.getInstance().load("weixin_basic");
//        Properties properties = new Properties();
//        try {
//            properties.load(ClassLoader.getSystemResourceAsStream("weixin_basic.properties"));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        WeixinContext.getInstance().setAppId(properties.getProperty("appID"));
        WeixinContext.getInstance().setAppSecret(properties.getProperty("appsecret"));
        WeixinContext.getInstance().setBaseUrl(properties.getProperty("base_url"));
        WeixinContext.getInstance().setToken(properties.getProperty("weixin_token"));
    }

    public static String replaceAccessTokenUrl(String url){
        return url.replace("ACCESS_TOKEN",WeixinContext.getInstance().getAccessToken().getAccess_token());
    }

    /**
     * 检查请求是否成功
     * @return
     */
    public static boolean checkRequestSucc(String content){
        try {
            JsonNode jn = JsonUtil.getMapper().readTree(content);
            if(!jn.has("errcode")){
                return true;
            }
            if(jn.get("errcode").asInt() == 0){
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static int getRequestCode (String content) {
        try {
            JsonNode jn = JsonUtil.getMapper().readTree(content);
            if(jn.has("errcode")) {
                return jn.get("errcode").asInt();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static String getRequestMsg(String content) {
        try {
            JsonNode jn = JsonUtil.getMapper().readTree(content);
            if(jn.has("errcode")) {
                return jn.get("errmsg").asText();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String sendPost(String url,String content,String type) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            StringEntity entity = new StringEntity(content, ContentType.create(type,"UTF-8"));
            post.addHeader("Content-Type",type);
            post.setEntity(entity);
            response = client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            if(status>=200&&status<300) {
                String str = EntityUtils.toString(response.getEntity());
                return str;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(client!=null) {
                    client.close();
                }
                if(response!=null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String sendJsonPost(String url,String content){
        return sendPost(url,content,"application/json");
    }

    public static String sendXmlPost(String url,String content){
        return sendPost(url,content,"application/xml");
    }

    public static String sendGet(String url) {
        HttpGet get = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        try {
            client = HttpClients.createDefault();
            get = new HttpGet(url);
            response = client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode>=200&&statusCode<300) {
                HttpEntity entity = response.getEntity();
                String content = EntityUtils.toString(entity,"utf-8");
                return content;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(response!=null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(client!=null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
}
